import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    console.log('响应数据:', res)

    // 成功状态码
    const successCodes = ['2000', '2001', '2002']

    // 如果返回的是成功状态码，直接返回数据
    if (successCodes.includes(res.code)) {
      return res
    }

    // 完整记录响应数据用于调试
    console.log('完整响应数据:', { response, res })

    // 错误状态码映射
    const errorMessages = {
      // 通用相关错误
      '4000': '请求参数错误',
      '4001': '未授权访问',
      '4003': '权限不足',
      '4004': '资源不存在',
      '4009': '资源冲突',
      '4022': '业务逻辑错误',

      // 登录相关错误
      '4031': '用户名或密码错误',
      '4032': '用户不存在',
      '4033': '账号已被禁用',
      '4034': '账号已被锁定',
      '4035': '账号已过期',
      '4036': '密码已过期',

      // 注册相关错误
      '4091': '用户名已存在',
      '4092': '邮箱已存在',
      '4093': '手机号已存在',

      // 认证相关错误
      '4011': '登录已过期',
      '4012': '无效的登录凭证',
      '4051': '权限不足',

      // 服务器错误
      '5000': '服务器内部错误',
      '5003': '服务暂不可用'
    }

    // 获取对应的错误消息
    const message = errorMessages[res.code] || res.message || '操作失败'

    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })

    // 需要重新登录的状态码
    const reLoginCodes = ['4034', '4035', '4036']
    if (reLoginCodes.includes(res.code)) {
      // to re-login
      MessageBox.confirm(
        '登录状态已失效，您可以取消停留在当前页面，或重新登录',
        '重新登录',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }

    return Promise.reject(new Error(message))
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
